<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="./css/reset.css">
  <link rel="stylesheet" href="./css/examination.css">
  <title>培训管理</title>
</head>
<script>
  function getParam(name) {
    return location.href.match(new RegExp('[?#&]' + name + '=([^?#&]+)', 'i')) ? RegExp.$1 : '';
  }
  var magicHtmlPath = '/obpm/html'
  var obpmFilePath = '/obpm'
  var appName = getParam('magicAppName')
  var test_paper_id = getParam('test_paper_id')
  var anti_cheating_settings = getParam('anti_cheating_settings')
  var exam_id = getParam('exam_id')
  var type = getParam('type')
  var examType = getParam('examType')
  var timer = null
  var maxtime = 60*60
  var accessToken = getParam('accessToken')
  document.cookie = "accessToken=" + accessToken + ";path=/";
  localStorage.setItem("accessToken", accessToken)
  var ajax = function (data) {
    return new Promise((resolve, reject) => {
      var xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (
            (xhr.status >= 200 && xhr.status < 300) ||
            xhr.status === 304
          ) {
            // resolve(xhr.responseText);
            data.success(xhr.responseText);
          } else {
            reject(xhr.status);
          }
        } else {
          // HTTP请求还在继续...
        }
      };
      xhr.open(data.methods, data.url, data.async);
      xhr.setRequestHeader("content-type", "application/json");

      delete data.methods;
      delete data.url;
      xhr.send(JSON.stringify(data.data));
    });
  };
  var allData = {} //所有数据
  var externalFlag = false //判断是不是分享的外部考试
  var full_name = ''
  var cell_phone = ''
  if(examType == 'external') {
    externalFlag = true
  }
  var question_idArr = [] //试题的id数组
  //一小时倒计时
  function countDown() {
    if(maxtime >= 0) {
      let minutes = Math.floor(maxtime/60)
      let seconds = Math.floor(maxtime%60)
      let msg = minutes + ':' + seconds
      let examTime = document.getElementsByClassName('examTime')[0]
      examTime.innerHTML = msg
      --maxtime
    }else {
      //auto 自动提交
      onSbmit('auto')
      clearInterval(timer)
    }
  }
  //开始考试
  function startToTest() {
    debugger
    full_name = document.getElementById('full_name').value
    cell_phone = document.getElementById('cell_phone').value
    if(!full_name) {
      document.getElementById('full_name_error').style.display = ''
      return
    } 
    if(!cell_phone) {
      document.getElementById('full_name_error').style.display = 'none'
      document.getElementById('cell_phone_error').style.display = ''
      document.getElementById('cell_phone_error').innerHTML = '请填写您的手机号'
      return
    }else {
      let phoneReg =/^1\d{10}$/;
      if(!phoneReg.test(cell_phone)) {
        document.getElementById('cell_phone_error').style.display = ''
        document.getElementById('cell_phone_error').innerHTML = '您的手机号不合法'
        return
      }
    }
    document.getElementById('full_name_error').style.display = 'none'
    document.getElementById('cell_phone_error').style.display = 'none'
    if(full_name && cell_phone) {
      let header = document.getElementsByClassName('header')[0]
      header.style.display = 'block'
      let examContent = document.getElementsByClassName('examContent')[0]
      examContent.style.display = 'block'
      let examContent2 = document.getElementsByClassName('examContent2')[0]
      examContent2.style.display = 'none'
      let submitData = {
        data: {
          action:'开始考试',
          exam_id:exam_id,
          full_name: full_name,
          cell_phone: cell_phone,
          test_paper_id:test_paper_id,
        }
      }
      let test = {
        methods: "post",
        url: `${obpmFilePath}/magic-api/${appName}/exam_submit`,
        async: true,
        data:submitData,
        success: function (result) {
          if(JSON.parse(result).errcode == '200') {
            if(allData.exam_info.exam_duration != 0) {
              let examTime = document.getElementsByClassName('examTime')[0]
              examTime.innerHTML = allData.exam_info.exam_duration
              maxtime = allData.exam_info.exam_duration
              timer = setInterval("countDown()",1000)
            }
          }else {
            alert(JSON.parse(result).errmsg)
          }
        }
      }
      ajax(test)
      externalFlag = false
    }else {
      alert('请填写您的姓名和手机号!')
    }
    console.log('1111')
  }
  //定义一个函数
  function exist(num, arr1) {
    for (var j = 0; j < arr1.length; j++) {
      if (num === arr1[j]) {
        return false; //如果传过来的元素在arr1中能找到相匹配的元素，我们返回fasle
      }
    }
    return true; //如果不能找到相匹配的元素，返回true
  }
  //提交
  function onSbmit(auto) {
    // auto 倒计时结束自动提交
    let inputArr = document.getElementsByClassName('examContent')[0].getElementsByClassName('onceOption')
    // confirm('本试卷共' + question_idArr.length + '道试题你已答题完成，是否确认提交')
    let answers = {}
    let answer_list = []
    for(let i = 0; i < inputArr.length; i ++) {
      let textBox = inputArr[i].getElementsByTagName('input')[0] || inputArr[i].getElementsByTagName('textarea')[0]
      if(textBox.type == 'radio' || textBox.type == 'checkbox') {
        if(textBox.checked) {
          if(answers[textBox.name]) {
            answers[textBox.name].push(textBox.value)
          }else {
            answers[textBox.name] = []
            answers[textBox.name].push(textBox.value)
          }
        }
      }else { 
        if(textBox.value) {
          if(answers[textBox.name]) {
            answers[textBox.name].push(textBox.value)
          }else {
            answers[textBox.name] = []
            answers[textBox.name].push(textBox.value)
          }
        }
      }
    }
    let answersKeyArr = [] //已填的题目的id
    for(let key in answers) {
      let obj = {
        'test_questions_id':key,
        'answer':answers[key].join(';')
      }
      if(auto) {
        answersKeyArr.push(key)
        answer_list.push(obj)
      }else {
        document.getElementById(key).style.display = 'none'
        answersKeyArr.push(key)
        answer_list.push(obj)
      }
    }
    for (let m = 0; m < question_idArr.length; m++) {
      //我们将question_idArr中的元素依次放入函数中进行比较，然后接收函数的返回值
      if (exist(question_idArr[m], answersKeyArr)) { //如果返回的值是true,证明改m索引的选项不在answersKeyArr数组里
        if(auto) {
          let obj = {
            'test_questions_id':question_idArr[m],
            'answer':''
          }
          answer_list.push(obj)
        }else {
          document.getElementById(question_idArr[m]).style.display = ''
        }
      }
    }
    if(answer_list.length != question_idArr.length) {
      return
    }
    console.log(answers,'answers')
    console.log(answer_list,'answer_list')
    if(auto) {
      exam_submit(answer_list)
      alert('考试时间到，已为您自动提交试卷')
    }else {
      if(confirm('本试卷共' + question_idArr.length + '道试题你已答题完成，是否确认提交')) {
        exam_submit(answer_list)
      }
    }
  }
  function exam_submit(answer_list) {
    let submitData = {
        data: {
          action:'结束考试',
          exam_id:exam_id,
          full_name:full_name,
          cell_phone:cell_phone,
          test_paper_id:test_paper_id,
          answer_list:answer_list,
        }
      }
      let test = {
        methods: "post",
        url: `${obpmFilePath}/magic-api/${appName}/exam_submit`,
        async: true,
        data:submitData,
        success: function (result) {
          if(JSON.parse(result).errcode == '200') {
            alert('提交成功')
            let main = document.getElementById('main')
            main.innerHTML = '<div style="height: 100%;display: flex;align-items: center;font-size: 26px;justify-content: center;"><div style="width:50%;">星光不问赶路人，时光不负有心人；恭喜考试成功！</div></div>'
          }
        }
      }
      ajax(test)
  }
  function getExam() {
    let data = {
      test_paper_id: test_paper_id,
      anti_cheating_settings:anti_cheating_settings,
      exam_id:exam_id,
    }
    let exam = {
      methods: "post",
      url: `${obpmFilePath}/magic-api/${appName}/exam_details`,
      async: true,
      data:data,
      success: function (result) {
        if(JSON.parse(result).data) {
          allData = JSON.parse(result).data
          let datas = JSON.parse(result).data.exam_list
          let exam_info = JSON.parse(result).data.exam_info
          let examName = document.getElementsByClassName('examName')[0]//考试名字
          examName.innerHTML = exam_info.exam_name
          let examTime = document.getElementsByClassName('examTime')[0]
          let examContent = document.getElementsByClassName('examContent')[0]
          let html = ''
          for(let i = 0; i < datas.length; i++) {
            if(datas[i].question_type == '单选题' || datas[i].question_type == '判断题') {
              let options = datas[i].options
              let optionsHtml = ''
              for(let j = 0; j < options.length; j ++) {
                optionsHtml +=  `
                  <div class="onceOption"><input type="radio" name="${datas[i].question_id}" value="${options[j]}">${String.fromCharCode(65+j)}、${options[j]}</div>
                `
              }
              html += `
                <div class="exameOnce">
                  <div class="examTopic"><span class="order">${i+1}、</span>${datas[i].question_type}：${datas[i].question_name}     (分值：${datas[i].score})</div>
                  <div class="examOption">
                    ${optionsHtml}
                  </div>
                  <span class="exameError" id="${datas[i].question_id}" style="display:none;">请至少选择一个选项</span>
                </div>
              `
            }else if(datas[i].question_type == '多选题') {
              let options = datas[i].options
              let optionsHtml = ''
              for(let j = 0; j < options.length; j ++) {
                optionsHtml +=  `
                  <div class="onceOption"><input type="checkbox" name="${datas[i].question_id}" value="${options[j]}">${String.fromCharCode(65+j)}、${options[j]}</div>
                `
              }
              html += `
                <div class="exameOnce">
                  <div class="examTopic"><span class="order">${i+1}、</span>${datas[i].question_type}：${datas[i].question_name}     (分值：${datas[i].score})</div>
                  <div class="examOption">
                    ${optionsHtml}
                  </div>
                  <span class="exameError" id="${datas[i].question_id}" style="display:none;">请至少选择一个选项</span>
                </div>
              `
            }else if(datas[i].question_type == '填空题') {
              html += `
              <div class="exameOnce">
                <div class="examTopic"><span class="order">${i+1}、</span>${datas[i].question_type}：${datas[i].question_name}     (分值：${datas[i].score})</div>
                <div class="examOption">
                  <div class="onceOption textInput"><input type="text" name="${datas[i].question_id}"></div>
                </div>
                <span class="exameError" id="${datas[i].question_id}" style="display:none;">请填写内容</span>
              </div>
              `
            }else {
              html += `
              <div class="exameOnce">
                <div class="examTopic"><span class="order">${i+1}、</span>问答题：${datas[i].question_name}      (分值：${datas[i].score})</div>
                <div class="examOption">
                  <div class="onceOption textInput"><textarea rows="5" name="${datas[i].question_id}"></textarea></div>
                </div>
                <span class="exameError" id="${datas[i].question_id}" style="display:none;">请填写内容</span>
              </div>
              `
            }
            question_idArr.push(datas[i].question_id)
          }
          examContent.innerHTML = html
          if(externalFlag) {
            debugger
            let header = document.getElementsByClassName('header')[0]
            header.style.display = 'none'
            examContent.style.display = 'none'
            let examContent2 = document.getElementsByClassName('examContent2')[0]
            examContent2.style.display = 'flex'
            examContent2.style.flexDirection = 'column'
            examContent2.style.alignItems = 'center'
            examContent2.style.height = 'calc(100% - 44px)'
            examContent2.innerHTML = `
              <div class="exameOnce">
                <div class="examTopic"><span class="order">1、</span>请填写您的姓名</div>
                <div class="examOption">
                  <div class="onceOption textInput"><input type="text" name="full_name" id="full_name" autocomplete="off"></div>
                </div>
                <span class="exameError" id="full_name_error" style="display:none;">请填写您的姓名</span>
              </div>
              <div class="exameOnce">
                <div class="examTopic"><span class="order">2、</span>请填写您的手机号</div>
                <div class="examOption">
                  <div class="onceOption textInput"><input type="text" name="cell_phone" id="cell_phone" autocomplete="off"></div>
                </div>
                <span class="exameError" id="cell_phone_error" style="display:none;">请填写您的手机号</span>
              </div>
              <div class="exameOnce" style="text-align:center;margin-top:20px;"><span class="startBtn" onclick="startToTest()">开始考试</span></div>
            `
          }else {
            if(type) { //type有值要多开始考试的接口
              let submitData = {
                data: {
                  action:'开始考试',
                  exam_id:exam_id,
                  test_paper_id:test_paper_id,
                }
              }
              let test = {
                methods: "post",
                url: `${obpmFilePath}/magic-api/${appName}/exam_submit`,
                async: true,
                data:submitData,
                success: function (result) {
                  if(JSON.parse(result).errcode == '200') {
                    if(exam_info.exam_duration != 0) {
                      examTime.innerHTML = exam_info.exam_duration
                      maxtime = exam_info.exam_duration
                      timer = setInterval("countDown()",1000)
                    }
                  }else {
                    alert(JSON.parse(result).errmsg)
                  }
                }
              }
              ajax(test)
            }
          }
        }
      }
    }
    ajax(exam); 
  }
</script>
<body onload="getExam()">
  <div id="main">
    <div class="header">
      <span class="btn" onclick="onSbmit()">提交</span>
    </div>
    <div class="content">
      <div class="examHeader">
        <div class="examName"></div>
        <div class="examTime"></div>
      </div>
      <div class="examContent">
      </div>
      <div class="examContent2">
      </div>
    </div>
  </div>
</body>
</html>